using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;

namespace Tasks
{
	public class ParallelTasks : Tasks
	{
		public ParallelTasks()
		{
			this.listOfStacks = new List<Stack<IEnumerator>>();
		}

		//[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public event Action onComplete;

		public override IEnumerator GetEnumerator()
		{
			base.isRunning = true;
			this.listOfStacks.Clear();
			foreach (IEnumerator t in base.registeredEnumerators)
			{
				Stack<IEnumerator> stack2 = new Stack<IEnumerator>();
				stack2.Push(t);
				this.listOfStacks.Add(stack2);
			}
			base.registeredEnumerators.Clear();
			UnityEngine.Debug.Log("Parallel Tasks Started, number of tasks: " + this.listOfStacks.Count);
			while (this.listOfStacks.Count > 0)
			{
				for (int i = 0; i < this.listOfStacks.Count; i++)
				{
					Stack<IEnumerator> stack = this.listOfStacks[i];
					if (stack.Count > 0)
					{
						IEnumerator ce = stack.Peek();
						if (!ce.MoveNext())
						{
							stack.Pop();
						}
						else if (ce.Current != null && ce.Current != ce)
						{
							if (ce.Current is IEnumerable)
							{
								stack.Push(((IEnumerable)ce.Current).GetEnumerator());
							}
							else if (ce.Current is IEnumerator)
							{
								stack.Push(ce.Current as IEnumerator);
							}
						}
						yield return null;
					}
					else
					{
						this.listOfStacks.RemoveAt(i);
						i--;
					}
				}
			}
			UnityEngine.Debug.Log("All Parallel Tasks Ended");
			base.isRunning = false;
			if (this.onComplete != null)
			{
				this.onComplete();
			}
			yield break;
		}

		private List<Stack<IEnumerator>> listOfStacks;
	}
}
